package cn.tuling.order.controller;


import cn.tuling.order.enums.OrderStatus;
import cn.tuling.order.feign.AccountService;
import cn.tuling.order.feign.StorageService;
import cn.tuling.order.po.Order;
import cn.tuling.order.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wuyanzhao
 * @since 2021-12-25
 */
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private StorageService storageService;

    @PostMapping("/save")
    @GlobalTransactional(name = "saveOrder")
    public Order saveOrder(@RequestBody Order order) {
        log.info("用户下单，当前 XID：{}", RootContext.getXID());

        order.setStatus(OrderStatus.INIT.name().toLowerCase());
        boolean save = orderService.save(order);
        log.info("保存订单{}", save ? "成功" : "失败");

        // 扣减库存
        storageService.deduct(order);

        // 扣减余额
        accountService.debit(order);

        //更新订单状态
        Order updateOrder = new Order();
        updateOrder.setStatus(OrderStatus.SUCCESS.name().toLowerCase());
        orderService.update(updateOrder, new QueryWrapper<>(order));

        return order;
    }
}

